package de.karlNet.login;

import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.ldap.AuthenticationException;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.stereotype.Controller;

import de.karlNet.sambamanager.ldapController.commands.BaseCommand;

@Controller
@Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class LoginCommand extends BaseCommand {

	
	@Autowired
	private LdapContextSource contextSource;
	@Value("${ldap.username}")
	private String originalUsername;

	@Value("${ldap.password}")
	private String originalPassword;

	public boolean login(String username, String password) {
		this.contextSource.setUserDn(username);
		this.contextSource.setPassword(password);
		if(username==null || password==null) {
			return false;
		}
		try {
			this.ldapTemplate.search(this.baseDN, "(objectclass=*)",
					SearchControls.OBJECT_SCOPE, new AttributesMapper() {

						@Override
						public Object mapFromAttributes(Attributes arg0)
								throws NamingException {
							return null;
						}
					});
		} catch (AuthenticationException e) {
			this.reset();
			return false;
		}
		return true;
	}
	
	public void reset() {
		this.contextSource.setUserDn(this.originalUsername);
		this.contextSource.setPassword(this.originalPassword);
	}
}
